package ijij41.network;

import ijij41.togetherTrain.participate.*;
import ijij41.togetherTrain.resource.*;

import java.io.*;
import java.util.*;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.json.*;

import android.util.*;

public class NetworkRequester {

	private static NetworkRequester instance;

	private NetworkRequester() {
	}

	public static NetworkRequester getInstance() {
		if (instance == null)
			instance = new NetworkRequester();
		return instance;
	}

	public ArrayList<TrainListRow> getTrainList(String time,
			String startStation, String endStation, String numPerson) {

		ArrayList<TrainListRow> arraylist = new ArrayList<TrainListRow>();

		StringBuffer sb = new StringBuffer();

		try {

			// String line =
			// getStringFromUrl("http://cats-test4.kaist.ac.kr/getTrainList?start_time=10:00&start_station=%EC%84%9C%EC%9A%B8&dest_station=%EB%B6%80%EC%82%B0");
			String line = getStringFromUrl("http://cats-test4.kaist.ac.kr/getTrainList?start_time="
					+ time
					+ "&start_station="
					+ startStation
					+ "&dest_station=" + endStation + "");

			JSONObject object = new JSONObject(line);
			Log.v("TRAIN_NETWORK", "getTrainList String : " + line);

			JSONArray hobbyArray = new JSONArray(object.getString("train"));
			for (int i = 0; i < hobbyArray.length(); i++) {

				JSONObject obj = new JSONObject(hobbyArray.getString(i));

				TrainListRow train = new TrainListRow();

				train.setTrainNum(obj.getString("train_num"));
				train.setStartStation(obj.getString("start_station"));
				train.setStartTime(obj.getString("start_time"));
				train.setEndStation(obj.getString("end_station"));
				train.setEndTime(obj.getString("end_time"));

				arraylist.add(train);

			}
			Log.v("TRAIN_NETWORK", "Complete list : " + arraylist.size());

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return arraylist;
	}

	private String getStringFromUrl(String url)
			throws UnsupportedEncodingException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				getInputStreamFromUrl(url, "euc-kr")));

		StringBuffer sb = new StringBuffer();
		try {
			String line = null;

			while ((line = br.readLine()) != null) {
				Log.v("TRAIN_NETWORK", line);
				sb.append(line);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	private InputStream getInputStreamFromUrl(String url, String string) {

		InputStream contentStream = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(new HttpGet(url));
			contentStream = response.getEntity().getContent();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return contentStream;
	}

	// TODO [Server] createRoom쪽에 Trasaction 처리가 필요함

	// 정확히 일치 하는 방을 찾는다. (시간에 가능한 열차들 리스트 중에서 하나의 시간때를 정해서 들어 온것이므로, 해당
	// 날짜,시간,출발,도착 역이 모두 같은것의 정보를 가쟈온다)
	public ArrayList<RoomListRow> getRoomList(String date, String trainNum,
			String startTime, String startStation, String endTime,
			String endStation) {

		ArrayList<RoomListRow> arraylist = new ArrayList<RoomListRow>();

		try {

			String query = "http://cats-test4.kaist.ac.kr/getRoomList?"
					+ "num_train=" + trainNum + "&start_time=" + startTime
					+ "&start_station=" + startStation + "&dest_time="
					+ endTime + "&dest_station=" + endStation + "&date=" + date;

			Log.v("TRAIN_NETWORK", "getRoomList Query String : " + query);

			String line = getStringFromUrl(query);

			JSONObject object = new JSONObject(line);
			Log.v("TRAIN_NETWORK", "getRoomList Result String : " + line);

			// TODO DB 퀄리 생성, WEB생성, Application 생성

			JSONArray jsonArray = new JSONArray(object.getString("roomlist"));
			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject obj = new JSONObject(jsonArray.getString(i));

				RoomListRow room = new RoomListRow();

				room.setIdx(obj.getString("idx"));
				room.setMaster_id(obj.getString("user_id"));
				room.setRoom_num(obj.getString("room_num"));
				room.setReservationPersonNum(obj.getString("num_member"));
				room.setMaxNumMember(obj.getString("max_num_member"));

				room.setTrainNum(trainNum);
				room.setStartStation(startStation);
				room.setStartTime(startTime);
				room.setEndStation(endStation);
				room.setEndTime(endTime);

				arraylist.add(room);

			}

			Log.v("TRAIN_NETWORK", "Complete list : " + arraylist.size());

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return arraylist;
	}

	public boolean createNewRoom(String date, String num_train,
			String start_time, String start_station, String dest_time,
			String dest_station, String max_num_member, String master_id) {

		try {

			String query = "http://cats-test4.kaist.ac.kr/createRoom.php?"
					+ "date=" + date + "&num_train=" + num_train
					+ "&start_time=" + start_time + "&start_station="
					+ start_station + "&dest_time=" + dest_time
					+ "&dest_station=" + dest_station + "&master_user_id="
					+ master_id + "&max_num_member=" + max_num_member;

			Log.v("TRAIN_NETWORK", "createNewRoom Query String : " + query);

			String line = getStringFromUrl(query);
			Log.v("TRAIN_NETWORK", "getRoomList Result String : " + line);

			JSONObject object = new JSONObject(line);

			return object.getBoolean("createRoom");

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	public ArrayList<MyTicketRoomListRow> getMyTickets(String userId) {

		ArrayList<MyTicketRoomListRow> arraylist = new ArrayList<MyTicketRoomListRow>();

		try {

			String query = "http://cats-test4.kaist.ac.kr/getMyTicket.php?"
					+ "user_id=" + userId;

			Log.v("TRAIN_NETWORK", "getMyTickets Query String : " + query);

			String line = getStringFromUrl(query);
			Log.v("TRAIN_NETWORK", "getMyTickets Result String : " + line);

			JSONObject object = new JSONObject(line);

			// TODO 상수화 할 필요가 있다.
			JSONArray jsonArray = new JSONArray(object.getString("myTicket"));
			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject obj = new JSONObject(jsonArray.getString(i));

				MyTicketRoomListRow myRoom = new MyTicketRoomListRow();

				myRoom.setIdx(obj.getString("idx"));
				myRoom.setDate(obj.getString("date"));
				myRoom.setMaster_id(obj.getString("user_id"));
				myRoom.setIsMaster(obj.getString("master"));
				myRoom.setRoom_num(obj.getString("room_num"));

				myRoom.setCurrentNumMember(obj.getString("current_num_member"));
				myRoom.setMaxNumMember(obj.getString("max_num_member"));

				myRoom.setTrainNum(obj.getString("num_train"));
				myRoom.setStartStation(obj.getString("start_station"));
				myRoom.setStartTime(obj.getString("start_time"));
				myRoom.setEndStation(obj.getString("dest_station"));
				myRoom.setEndTime(obj.getString("dest_time"));

				arraylist.add(myRoom);

			}

			return arraylist;

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public JSONObject getRoomView(String room_idx) {

		try {

			String query = "http://cats-test4.kaist.ac.kr/getRoomView.php?"
					+ "room_idx=" + room_idx;

			Log.v("TRAIN_NETWORK", "getRoomView Query String : " + query);

			String line = getStringFromUrl(query);
			Log.v("TRAIN_NETWORK", "getRoomView Result String : " + line);

			JSONObject object = new JSONObject(line);

			JSONArray jsonArray = new JSONArray(object.getString("roomView"));
			JSONObject returnJsonObj = new JSONObject(jsonArray.getString(0));

			return returnJsonObj;

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	
	public int leaveRoom(String room_idx, String userId) {

		
				
		try {
			
			String query = "http://cats-test4.kaist.ac.kr/leaveRoom.php?"
					+ "room_idx=" + room_idx
					+ "&user_id=" + userId;

			Log.v("TRAIN_NETWORK", "leaveRoom Query String : " + query);

			String line = getStringFromUrl(query);
			Log.v("TRAIN_NETWORK", "leaveRoom Result String : " + line);

			JSONObject object = new JSONObject(line);
			int returnCode = object.getInt("leaveRoom");  

			return returnCode;    //TODO 1 정상  -1 비정상

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		
		return -1;
		
		
		
		
		
		
		
	}

	public int participateRoom(String room_idx, String userId) {

		try {

			String query = "http://cats-test4.kaist.ac.kr/participateRoom.php?"
					+ "room_idx=" + room_idx
					+ "&user_id=" + userId;
			

			Log.v("TRAIN_NETWORK", "participateRoom Query String : " + query);

			String line = getStringFromUrl(query);
			Log.v("TRAIN_NETWORK", "participateRoom Result String : " + line);

			JSONObject object = new JSONObject(line);

			//JSONArray jsonArray = new JSONArray(object.getString("participateRoom"));
			//JSONObject returnJsonObj = new JSONObject(jsonArray.getString(0));
			//int returnCode = returnJsonObj.getInt("return_value");
			int returnCode = object.getInt("participateRoom");   //TODO 다시 꾸밀까???

			return returnCode;    //TODO 코드화 시켜야 한다. 1 정상 -1 비정상 -2 이미 있음  -3 수용 인원이 다참 DB는 transaction화를 다 시켜야 한다. 특히 여러개의 쿼리가 있는것에 대해

		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		
		return -1;
	}
}
